define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuerp/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'kuerp/expense/index' + location.search,
                    add_url: 'kuerp/expense/add',
                    edit_url: 'kuerp/expense/edit',
                    del_url: 'kuerp/expense/del',
                    multi_url: 'kuerp/expense/multi',
                    import_url: 'kuerp/expense/import',
                    table: 'kuerp_expense',
                }
            });

            var table = $("#table");
            var adminlist = Config.adminlist;
            var admin_id = Config.admin_id;
            var has_pay_auth = Config.pay_auth;
            var enable_approvedEdit = Config.approvedEdit;
            var edit_auth = Config.edit_auth;
            var del_auth = Config.del_auth;
            var backApply_auth = Config.backApply_auth;
            var examine_admins = Config.examine_admins;

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                search:false,
                columns: [
                    [
                        {checkbox: true},
                        // {field: 'id', title: __('Id')},
                        {field: 'expense_code', title: __('Expense_code'), operate: 'LIKE'},
                        // {field: 'admin_id', title: __('Admin_id'), formatter: function(value, row, index){
                        //     return row.admin.nickname || ''
                        // }},
                        {field: 'admin_id', title: __('Admin_id'), formatter:Table.api.formatter.label,searchList:adminlist},
                        {field: 'cost', title: __('Cost'), operate:'BETWEEN'},
                        {field: 'income_month', title: __('Income_month'), operate:'eq', addclass:'datetimepicker',data:'data-date-format="YYYY-MM"', formatter: Table.api.formatter.datetime,datetimeFormat:'YYYY-MM'},
                        {field: 'start_time', title: __('Start_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: function(value, row, index) {
                            return row.start_time_text;
                        }},
                        {field: 'end_time', title: __('End_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: function(value, row, index) {
                            return row.end_time_text;
                        }},
                        
                        // {field: 'did', title: __('Did')},
                        {field: 'pay_status', title: __('Pay_status'),formatter:Table.api.formatter.status,searchList:{"0":__('Pay_status 0'),"1":__('Pay_status 1')}},
                        {field: 'remark', title: __('Remark'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content, visible:false},
                        {field: 'check_last_uid', title: __('最后审核人'), formatter: function(value, row, index){
                            return row.last_checkadmin && (row.last_checkadmin.nickname || '')
                        }, searchList:examine_admins},
                        {field: 'check_status', title: __('Check_status'),formatter:Table.api.formatter.status,custom:{"0":"", "1":"info", "2":"success", "3":"danger", "4":"info"},searchList:{"0":__('Check_status 0'),"1":__('Check_status 1'),"2":__('Check_status 2'),"3":__('Check_status 3'),"4":__('Check_status 4')}},
                        {field: 'createtime', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    text: __(''),
                                    title: '详情',
                                    classname: 'btn btn-xs btn-info  btn-dialog',
                                    icon: 'fa fa-file-o',
                                    url: function (row, column) { //row 表格接收到的数据
                                        return "kuerp/expense/detail?ids=" + row.id; //弹窗的对应后台控制器方法 这里是默认index方法 加id参数
                                    },
                                    extend: 'data-area=\'["90%","90%"]\'',
                                    refresh: true
                                },
                                {
                                    name: 'edit',
                                    text: __(''),
                                    classname: 'btn btn-xs btn-success  btn-dialog',
                                    icon: 'fa fa-pencil',
                                    url: function (row, column) { //row 表格接收到的数据
                                        return "kuerp/expense/edit?ids=" + row.id; //弹窗的对应后台控制器方法 这里是默认index方法 加id参数
                                    },
                                    visible:function(row){
                                        return row.pay_status == 0 && (([0, 3].indexOf(row.check_status) > -1 && edit_auth) || (row.check_status == 2 && enable_approvedEdit));
                                    },
                                    extend: 'data-area=\'["90%","90%"]\'',
                                    refresh: true
                                },
                                {
                                    name: 'del',
                                    text: __(''),
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    icon: 'fa fa-trash',
                                    title: '删除',
                                    confirm: '确定删除此项？',
                                    url: function (row, column) { //row 表格接收到的数据
                                        return "kuerp/expense/del?ids=" + row.id; //弹窗的对应后台控制器方法 这里是默认index方法 加id参数
                                    },
                                    visible:function(row){
                                        return [0,3].indexOf(row.check_status) != -1 && del_auth && row.pay_status != 1;
                                    },
                                    refresh: true
                                },
                                // {
                                //     name: 'backApply',
                                //     text: __('撤回'),
                                //     classname: 'btn btn-xs btn-info btn-ajax',
                                //     icon: 'fa fa-undo',
                                //     url: function (row, column) { //row 表格接收到的数据
                                //         return "kuerp/expense/backApply?ids=" + row.id; //弹窗的对应后台控制器方法 这里是默认index方法 加id参数
                                //     },
                                //     visible:function(row){
                                //         return row.check_status == 3 && row.admin_id == admin_id && backApply_auth;
                                //     },
                                //     refresh: true
                                // },
                                {
                                    name: 'pay',
                                    text: __('标记为打款'),
                                    classname: 'btn btn-xs btn-success btn-ajax',
                                    icon: 'fa fa-check',
                                    confirm: '确定标记为已打款？',
                                    url: function (row, column) { //row 表格接收到的数据
                                        return "kuerp/expense/changePayStatus?ids=" + row.id; //弹窗的对应后台控制器方法 这里是默认index方法 加id参数
                                    },
                                    visible:function(row){
                                        return row.check_status == 2 && row.pay_status == 0 && has_pay_auth;
                                    },
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            
            //本地记录字段显示及宽度情况
            function tableColFilterAndWidth(dataKey) {
                // 初始化筛选状态
                var local = layui.data(dataKey);
                obj = table.bootstrapTable('getOptions');
                obj.columns[0].forEach(function(item) {
                    if (item.field) {
                        var hide_key = item.field;
                        if (hide_key in local) {
                            $('#table').bootstrapTable(local[hide_key] ? 'showColumn' : 'hideColumn', hide_key);
                        }
                    }
                });
                
                //记录筛选状态
                table.on('column-switch.bs.table', function(e, field, checked){
                    console.log('column-switch.bs.table', field, checked)
                    layui.data(dataKey, {key: field,value: checked})
                });
            }
            //当表格数据加载完成时
            table.on('load-success.bs.table', function (e, data) {
                //这里我们手动设置底部的值
                $("#money").text(data.extend.total_cost);
                $("#pass_cost").text(data.extend.pass_cost);
                $("#passing_cost").text(data.extend.passing_cost);
                $("#nopass_cost").text(data.extend.nopass_cost);
                $("#nopay_cost").text(data.extend.nopay_cost);
                $("#pay_cost").text(data.extend.pay_cost);
                tableColFilterAndWidth('table-expense')
            });

            
            $(".btn-add").data("area", ["100%", "100%"]); // 添加按钮
            //导出
            $(document).on("click", ".btn-export", function(){
                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var options = table.bootstrapTable('getOptions');
                var params=options.queryParams({});
                var all = options.totalRows;
                var sort = options.sortName+' '+options.sortOrder;
                var filter = params.filter;
                var op = params.op;
                Layer.confirm("请选择导出的选项", {
                    title   : '导出数据',
                    btn     : ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    success : function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    }, yes   : function (index, layero) {
                        if (ids.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        $.post('kuerp/expense/export', {sort:sort,ids : ids.join(","), isall : 1}, function (res) {
                            if(res.code == 1){
                                Layer.alert(res.msg);
                                window.location.href = res.data.filePath;
                                $.ajax({
                                    url: "kuerp/expense/export",
                                    data: { user_path: res.data.filePath},
                                    type: "post",
                                    success: function() {
                                        console.log('File deleted successfully!');
                                    }
                                });
                                Layer.close(index);
                                table.bootstrapTable('refresh');
                            }else{
                                Layer.alert(res.msg);
                            }
                        }, 'json');
                        return false;
                    },
                    btn2    : function (index, layero) {
                        if (page.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        var ids = [];
                        $.each(page, function (i, j) {
                            ids.push(j.id);
                        });
                        $.post('kuerp/expense/export', {sort:sort,ids : ids.join(","), isall : 2}, function (res) {
                            if(res.code == 1){
                                Layer.alert(res.msg);
                                window.location.href = res.data.filePath;
                                $.ajax({
                                    url: "kuerp/expense/export",
                                    data: { user_path: res.data.filePath},
                                    type: "post",
                                    success: function() {
                                        console.log('File deleted successfully!');
                                    }
                                });
                                Layer.close(index);
                                table.bootstrapTable('refresh');
                            }else{
                                Layer.alert(res.msg);
                            }
                        }, 'json');
                        return false;
                    },
                    btn3    : function (index, layero) {
                        if (page.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        $.post('kuerp/expense/export?filter='+filter+'&op='+op, {sort:sort,ids : ids.join(","), isall : 3}, function (res) {
                            if(res.code == 1){
                                Layer.alert(res.msg);
                                window.location.href = res.data.filePath;
                                $.ajax({
                                    url: "kuerp/expense/export",
                                    data: { user_path: res.data.filePath},
                                    type: "post",
                                    success: function() {
                                        console.log('File deleted successfully!');
                                    }
                                });
                                Layer.close(index);
                                table.bootstrapTable('refresh');
                            }else{
                                Layer.alert(res.msg);
                            }
                        }, 'json');
                        return false;
                    }
                })
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                // 绑定表单验证
                Form.api.bindevent($("form[role=form]"));

                $(".save").on('click', function(){
                    var check_status = $(this).data('status')
                    $('#c-check_status').val(check_status)
                    $('form').submit();
                })

                $(".faupload").data("upload-success", function(data, ret, up, file){
                    console.log('upload-success',data, ret, up, file)
                })

                $(document).on("fa.event.appendfieldlist", '.fieldlist', function(){
                    //通用的表单组件事件绑定和组件渲染
                    Form.events.selectpage($("form"));
                    Form.events.datetimepicker($("form"));
                });

                 // 监听删除行按钮点击事件
                 $(document).on("click", ".btn-remove", function(){
                    // 等待DOM更新完成后再计算总计
                    setTimeout(function(){
                        // 计算所有行的总计
                        var grandTotal = 0;
                        $('input[name$="[total_money]"]').each(function(){
                            var value = parseFloat($(this).val()) || 0;
                            grandTotal += value;
                        });
                        
                        // 更新显示
                        $('#total_money').text(grandTotal.toFixed(2));
                        var chineseAmount = numberToChinese(grandTotal);
                        $('#total_money_chinese').text(chineseAmount);
                    }, 100);
                });

                // 监听费用输入变化
                $(document).on("change keyup", ".fee", function(){
                    var $this = $(this);
                    var $row = $this.closest('tr');
                    
                    // 计算当前行的合计
                    var rowTotal = 0;
                    $row.find('.fee').each(function(){
                        var value = parseFloat($(this).val()) || 0;
                        rowTotal += value;
                    });
                    
                    // 更新当前行的合计
                    $row.find('input[name$="[total_money]"]').val(rowTotal.toFixed(2));
                    
                    // 计算所有行的总计
                    var grandTotal = 0;
                    $('input[name$="[total_money]"]').each(function(){
                        var value = parseFloat($(this).val()) || 0;
                        grandTotal += value;
                    });
                    
                    // 更新总费用到隐藏字段（如果需要）
                    $('#c-total_money').val(grandTotal.toFixed(2));
                    
                    // 可选：显示大写金额
                    var chineseAmount = numberToChinese(grandTotal);
                    $('#total_money_chinese').text(chineseAmount);
                    $('#total_money').text(grandTotal.toFixed(2));
                    // $('#amount-in-words').text('合计金额：' + grandTotal.toFixed(2) + '元(' + chineseAmount + ')');
                });
                $('#total_money_chinese').text(numberToChinese(parseFloat($('#total_money').text())));
                // 数字转中文大写函数
                function numberToChinese(number) {
                    var units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿'];
                    var chars = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
                    
                    var n = Math.floor(number);
                    var decimals = ((number % 1) * 100).toFixed(0);
                    var chineseStr = '';
                    
                    if (n > 0) {
                        var str = n.toString();
                        for (var i = 0; i < str.length; i++) {
                            var digit = parseInt(str[i]);
                            if (digit === 0) {
                                if (i < str.length - 1 && parseInt(str[i + 1]) !== 0) {
                                    chineseStr += chars[digit];
                                }
                            } else {
                                chineseStr += chars[digit] + units[str.length - 1 - i];
                            }
                        }
                        chineseStr += '元';
                    }
                    
                    
                    
                    if (decimals > 0) {
                        if (n === 0) {
                            chineseStr += '零元';
                        }
                        var jiao = Math.floor(decimals / 10);
                        var fen = decimals % 10;
                        if (jiao > 0) chineseStr += chars[jiao] + '角';
                        if (fen > 0) chineseStr += chars[fen] + '分';
                    } else {
                        if (n > 0) {
                            chineseStr += '整';
                        }
                    }
                    
                    return chineseStr;
                }
            }
        }
    };
    return Controller;
});
